from flask import request, Blueprint, render_template, redirect, url_for
from datetime import datetime, time
from models import ScheduledEvent, MonthlyBudget, Expense, db
from decimal import Decimal

scheduled_events_bp = Blueprint("scheduled_events", __name__, url_prefix="/scheduled_events")


@scheduled_events_bp.route("/")
def scheduled_events():
    db.session.remove()  # 确保使用新的 session
    events = ScheduledEvent.query.all()
    return render_template("scheduled_events.html", events=events)


@scheduled_events_bp.route("/add", methods=["GET", "POST"])
def add_scheduled_event():
    if request.method == "POST":
        try:
            interval_days = int(request.form.get("interval_days"))
            execution_time = request.form.get("execution_time")
            event_type = request.form.get("event_type")
            amount_str = request.form.get("amount")
            description = request.form.get("description", "")
            skip_weekends = request.form.get("skip_weekends") == "true"
            enabled = request.form.get("enabled") == "true"

            # 验证表单字段
            missing_fields = []
            if not interval_days:
                missing_fields.append("间隔天数")
            if not execution_time:
                missing_fields.append("执行时间")
            if not event_type:
                missing_fields.append("类型")
            if not amount_str:
                missing_fields.append("金额")

            if missing_fields:
                return "缺少必填字段: " + ", ".join(missing_fields), 400

            amount = Decimal(amount_str).quantize(Decimal('0.00'))
            
            # 验证时间格式
            try:
                execution_time_obj = datetime.strptime(execution_time, "%H:%M").time()
            except ValueError:
                return "时间格式不正确，应为 HH:MM 格式", 400

            new_event = ScheduledEvent(
                interval_days=interval_days,
                execution_time=execution_time_obj,
                event_type=event_type,
                amount=amount,
                description=description,
                skip_weekends=skip_weekends,
                enabled=enabled
            )
            
            db.session.add(new_event)
            db.session.commit()

            return redirect(url_for("scheduled_events.scheduled_events"))
        except Exception as e:
            db.session.rollback()
            return f"内部服务器错误: {e}", 500

    return render_template("scheduled_event_form.html", title="添加定时事件", action="add")


@scheduled_events_bp.route("/edit/<int:event_id>", methods=["GET", "POST"])
def edit_scheduled_event(event_id):
    event = ScheduledEvent.query.get_or_404(event_id)
    
    if request.method == "POST":
        try:
            interval_days = int(request.form.get("interval_days"))
            execution_time = request.form.get("execution_time")
            event_type = request.form.get("event_type")
            amount_str = request.form.get("amount")
            description = request.form.get("description", "")
            skip_weekends = request.form.get("skip_weekends") == "true"
            enabled = request.form.get("enabled") == "true"

            # 验证表单字段
            missing_fields = []
            if not interval_days:
                missing_fields.append("间隔天数")
            if not execution_time:
                missing_fields.append("执行时间")
            if not event_type:
                missing_fields.append("类型")
            if not amount_str:
                missing_fields.append("金额")

            if missing_fields:
                return "缺少必填字段: " + ", ".join(missing_fields), 400

            amount = Decimal(amount_str).quantize(Decimal('0.00'))
            
            # 验证时间格式
            try:
                execution_time_obj = datetime.strptime(execution_time, "%H:%M").time()
            except ValueError:
                return "时间格式不正确，应为 HH:MM 格式", 400

            # 更新事件
            event.interval_days = interval_days
            event.execution_time = execution_time_obj
            event.event_type = event_type
            event.amount = amount
            event.description = description
            event.skip_weekends = skip_weekends
            event.enabled = enabled
            
            db.session.commit()

            return redirect(url_for("scheduled_events.scheduled_events"))
        except Exception as e:
            db.session.rollback()
            return f"内部服务器错误: {e}", 500

    return render_template("scheduled_event_form.html", title="编辑定时事件", action="edit", event=event)


@scheduled_events_bp.route("/toggle/<int:event_id>", methods=["POST"])
def toggle_scheduled_event(event_id):
    try:
        event = ScheduledEvent.query.get_or_404(event_id)
        event.enabled = not event.enabled
        db.session.commit()
        return redirect(url_for("scheduled_events.scheduled_events"))
    except Exception as e:
        db.session.rollback()
        return f"切换定时事件状态时出错: {str(e)}", 500


# 用于删除定时事件
@scheduled_events_bp.route("/delete/<int:event_id>", methods=["POST"])
def delete_scheduled_event(event_id):
    try:
        event = ScheduledEvent.query.get_or_404(event_id)
        db.session.delete(event)
        db.session.commit()
        return redirect(url_for("scheduled_events.scheduled_events"))
    except Exception as e:
        db.session.rollback()
        return f"删除定时事件时出错: {str(e)}", 500